package util;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Charsets;
import org.apache.http.Header;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;

/**
 * @author
 * @version $Id: HttpUtils.java, v 0.1 2020-07-29 17:26 Exp $$
 */

@Component
public class HttpClientUtils {

    public static JSONObject doPost(String url, HashMap<String,String> headers, String params)throws Exception {

        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse httpResponse = null;

        try {
            //设置url、headers、params
            HttpPost httpPost = new HttpPost(new URIBuilder(url).build());
            if(Objects.nonNull(headers)){
                for(Map.Entry<String,String> header:headers.entrySet()){
                    httpPost.addHeader(header.getKey(),header.getValue());
                }
            }
            if(Objects.nonNull(params)){
                StringEntity se = new StringEntity(params,Charsets.UTF_8);
                se.setContentType("application/json;charset=UTF-8");
//                se.setContentEncoding();
                httpPost.setEntity(se);
            }

            // 执行请求
            httpResponse = httpClient.execute(httpPost);
            String content = null;
            if(Objects.nonNull(httpResponse)){
                // 请求成功

                if(Objects.nonNull(httpResponse.getEntity())) {
                    content = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
                }
            }

            return JSONObject.parseObject(content);
        }finally {
            // 释放资源
            if (httpResponse != null) httpResponse.close();
            if (httpClient != null) httpClient.close();
        }

    }

}
